﻿Public Class ConnectForm

    Private _pi As ProjectItem
    Private _oldConnectType As Integer

    Private Sub ConnectForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        For Each com As String In System.IO.Ports.SerialPort.GetPortNames()
            Me.cboCOM.Items.Add(com)
        Next

        _pi = MainForm.pi

        LoadData()

    End Sub

    Private Sub LoadData()
        _oldConnectType = _pi.connectType

        Select Case MainForm.readConfig("SystemType")
            Case 0, 2
                Select Case _pi.connectType
                    Case 0 '拨号
                        Me.optDial.Checked = True
                        Me.cboCOM.SelectedItem = "COM" & _pi.PhonePort
                        Me.txtPhone.Text = _pi.Phone

                    Case 1 '直连
                        Me.optCOM.Checked = True
                        Me.cboCOM.SelectedItem = "COM" & _pi.ComNumber

                    Case 2 'TCP
                        Me.optTcp.Checked = True
                        Me.txtIPAddress.Text = _pi.IPAddress
                        Me.nudIPPort.Value = _pi.IPPort
                    Case Else
                        Me.optTcp.Checked = True

                End Select
            Case 1

                Me.optTcp.Checked = True
                Me.txtIPAddress.Text = _pi.IPAddress
                Me.nudIPPort.Value = _pi.IPPort
                ' _oldConnectType = 2
            Case Else
        End Select

       
    End Sub

    Private Sub btnOk_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOk.Click
        Me.btnOk.Enabled = False

        If CheckValid() = True Then

            Select Case MainForm.readConfig("SystemType")
                Case 0, 2

                    If Save() = True Then
                        If Connect() = True Then
                            Me.DialogResult = Windows.Forms.DialogResult.OK

                            Me.Close()
                        End If
                    End If

                Case 1

                    If Connect() = True Then
                        Me.DialogResult = Windows.Forms.DialogResult.OK

                        Me.Close()
                    End If


                Case Else
            End Select

           
        End If





        Me.btnOk.Enabled = True
    End Sub
    '*****************************************************************************************************
    '2009年06月10日 李吉鹏修改 
    '******************************************************************************************************
    Private Function Save() As Boolean
        Try
            If Me.optCOM.Checked = True Then
                _pi.connectType = 1
                _pi.ComNumber = CInt(Me.cboCOM.SelectedItem.Substring(3))
                g_BackgroundUploadHistoryData_Com = IIf(KeyValuePairClass.GetValue(_pi.ProjectID, "BackgroundUploadHistoryData_Com").Equals("1"), True, False)
                g_BackgroundUploadAlarm_Com = IIf(KeyValuePairClass.GetValue(_pi.ProjectID, "BackgroundUploadAlarm_Com").Equals("1"), True, False)

                g_BackgroundUploadDiData_Com = IIf(KeyValuePairClass.GetValue(_pi.ProjectID, "g_BackgroundUploadDiData_Com").Equals("1"), True, False)


            ElseIf Me.optDial.Checked = True Then
                _pi.connectType = 0
                _pi.PhonePort = CInt(Me.cboCOM.SelectedItem.Substring(3))
                _pi.Phone = Me.txtPhone.Text
                g_BackgroundUploadHistoryData_Tel = IIf(KeyValuePairClass.GetValue(_pi.ProjectID, "BackgroundUploadHistoryData_Tel").Equals("1"), True, False)
                g_BackgroundUploadAlarm_Tel = IIf(KeyValuePairClass.GetValue(_pi.ProjectID, "BackgroundUploadAlarm_Tel").Equals("1"), True, False)

                g_BackgroundUploadDiData_Tel = IIf(KeyValuePairClass.GetValue(_pi.ProjectID, "g_BackgroundUploadDiData_Tel").Equals("1"), True, False)

            ElseIf Me.optTcp.Checked = True Then
                _pi.connectType = 2
                _pi.IPAddress = Me.txtIPAddress.Text
                _pi.IPPort = Me.nudIPPort.Value
                g_BackgroundUploadHistoryData_Tcp = IIf(KeyValuePairClass.GetValue(_pi.ProjectID, "BackgroundUploadHistoryData_Tcp").Equals("1"), True, False)
                g_BackgroundUploadAlarm_Tcp = IIf(KeyValuePairClass.GetValue(_pi.ProjectID, "BackgroundUploadAlarm_Tcp").Equals("1"), True, False)

                g_BackgroundUploadDiData_Tcp = IIf(KeyValuePairClass.GetValue(_pi.ProjectID, "g_BackgroundUploadDiData_Tcp").Equals("1"), True, False)

            End If
        Catch ex As Exception
            msg.ShowError("")
        End Try

        Dim strSql As String

        strSql = "UPDATE tbccProject SET " & _
                "ConnectType=?p0,ComNumber=?p1,phoneNumber=?p2,phonePort=?p4,IPAddress=?p5,IPPort=?p6 " & _
                "WHERE projectID=?p3"

        Dim p(6) As MySql.Data.MySqlClient.MySqlParameter
        For i As Integer = 0 To p.Length - 1
            p(i) = New MySql.Data.MySqlClient.MySqlParameter()
        Next

        p(0).ParameterName = "p0" : p(0).Value = _pi.connectType
        p(1).ParameterName = "p1" : p(1).Value = _pi.ComNumber
        p(2).ParameterName = "p2" : p(2).Value = _pi.Phone
        p(3).ParameterName = "p3" : p(3).Value = _pi.ProjectID
        p(4).ParameterName = "p4" : p(4).Value = _pi.PhonePort
        p(5).ParameterName = "p5" : p(5).Value = _pi.IPAddress
        p(6).ParameterName = "p6" : p(6).Value = _pi.IPPort

        If SqlHelper.ExecuteNonQuery(strSql, p) > 0 Then
            'If _pi.connectType <> _oldConnectType Then
            '  KeyValuePairClass.SetValue(_pi.ProjectID, "BackgroundUploadHistoryData", IIf(g_BackgroundUploadHistoryData, 1, 0))
            '  KeyValuePairClass.SetValue(_pi.ProjectID, "BackgroundUploadAlarm", IIf(g_BackgroundUploadAlarm, 1, 0))
            'End If

            Return True
        Else
            Return False
        End If
        '***************************************************************************************************
    End Function

    Private Function CheckValid() As Boolean
        '检查连接方式
        If Me.optCOM.Checked = False AndAlso Me.optDial.Checked = False AndAlso Me.optTcp.Checked = False Then
            msg.Show("请选择连接方式。")
            Me.optCOM.Focus()
            Return False
        End If

        '检查串口号
        If Me.optCOM.Checked = True OrElse Me.optDial.Checked = True Then
            If Me.cboCOM.SelectedIndex < 0 Then
                msg.Show("请选择串口号。")
                Me.cboCOM.Focus()
                Return False
            End If
        End If

        '检查电话号码
        If Me.optDial.Checked = True Then
            If Me.txtPhone.Text.Trim.Length <= 0 Then
                msg.Show("请输入电话号码。")
                Me.txtPhone.Focus()
                Return False
            End If
        End If

        '检查TCP参数
        If Me.optTcp.Checked = True Then
            '检查IP地址
            If Me.txtIPAddress.Text.Trim.Length <= 0 Then
                msg.Show("请输入IP地址。")
                Me.txtIPAddress.Focus()
                Return False
            End If
            '检查IP端口
            If Me.nudIPPort.Value <= 0 Then
                msg.Show("IP端口不能为零。")
                Me.nudIPPort.Focus()
                Return False
            End If
        End If

        Return True
    End Function

#Region " 连接函数 "

    Private Function Connect() As Boolean
        Return Connect(False)
    End Function
    Private Function Connect(ByVal isRetry As Boolean) As Boolean

        Select Case MainForm.readConfig("SystemType")
            ' Case 0, 2

            Case 1
                COMHelper.ConnectType = 2
                'TCP/IP
                Dim frm As New TcpConnectForm(isRetry)
                If frm.ShowDialog() <> Windows.Forms.DialogResult.OK Then
                    Return False
                End If
            Case Else
                COMHelper.ConnectType = _pi.connectType

                If _pi.connectType = 1 Then
                    '直连 
                    Me.Cursor = Cursors.WaitCursor
                    If InitCOM() = False Then
                        Me.Cursor = Cursors.Default
                        Return False
                    End If
                    Me.Cursor = Cursors.Default
                ElseIf _pi.connectType = 0 Then
                    '拨号
                    Dim frm As New DialForm("COM" & _pi.PhonePort.ToString(), _pi.Phone)
                    If frm.ShowDialog <> Windows.Forms.DialogResult.OK Then
                        Return False
                    End If
                Else
                    'TCP/IP
                    Dim frm As New TcpConnectForm(isRetry)
                    If frm.ShowDialog() <> Windows.Forms.DialogResult.OK Then
                        Return False
                    End If
                End If
        End Select



        

        Return True
    End Function

#Region " 直连方式 "

    Private Function InitCOM() As Boolean
        Dim com As String
        com = _pi.ComNumber.ToString()

        If com = "" Then
            msg.Show("请先配置串口")
            Return False
        End If

        If COMHelper.Instance.InitSerialPort(com.Replace("COM", ""), IO.Ports.Parity.Even) Then
            Return DirectConnect()
            'Return True
        Else
            msg.ShowError("初始化串口失败,请检查串口配置")
            Return False
        End If

    End Function

    Private Function DirectConnect() As Boolean
        Dim strResult As String

        For i As Integer = 0 To 2

            strResult = COMHelper.Instance.WriteCommand(UtilityClass.GetAuthCodeByte(_pi.AuthCode), 10, 10000)
            If strResult.IndexOf("AT^AUTH=OK") >= 0 Then
                Return True
            ElseIf strResult.ToUpper.IndexOf("ERROR") >= 0 Then
                msg.ShowError("与下位机的连接鉴权失败。")
                Return False
            End If

            System.Threading.Thread.Sleep(1000)
            Application.DoEvents()
        Next

        msg.ShowError("无法建立于下位机的连接")

        Return False
    End Function

#End Region

#End Region

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Me.Close()
    End Sub

    Private Sub optDial_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles optDial.CheckedChanged
        Me.pnlTCP.Enabled = False
        Me.pnlTCP.Visible = False
        Me.pnlCom.Enabled = True
        Me.pnlCom.Visible = True
        Me.pnlPhone.Enabled = True
        Me.pnlPhone.Visible = True
        Me.cboCOM.SelectedItem = "COM" & _pi.PhonePort
        Me.txtPhone.Text = _pi.Phone
    End Sub

    Private Sub optCOM_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles optCOM.CheckedChanged
        Me.pnlTCP.Enabled = False
        Me.pnlTCP.Visible = False
        Me.pnlPhone.Enabled = False
        Me.pnlPhone.Visible = False
        Me.pnlCom.Enabled = True
        Me.pnlCom.Visible = True
        Me.cboCOM.SelectedItem = "COM" & _pi.ComNumber
    End Sub

    Private Sub optTcp_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles optTcp.CheckedChanged
        Me.pnlCom.Enabled = False
        Me.pnlCom.Visible = False
        Me.pnlPhone.Enabled = False
        Me.pnlPhone.Visible = False
        Me.pnlTCP.Enabled = True
        Me.pnlTCP.Visible = True
        Me.txtIPAddress.Text = _pi.IPAddress
        Me.nudIPPort.Value = _pi.IPPort
    End Sub

    Private Sub btnConnectConfig_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnectConfig.Click
        Dim parameters(2) As String

        parameters(0) = KeyValuePairClass.GetValue(_pi.ProjectID, "ClientSocket_Heartbeat_IdleTime")
        parameters(1) = KeyValuePairClass.GetValue(_pi.ProjectID, "ClientSocket_Heartbeat_WaitTime")
        parameters(2) = KeyValuePairClass.GetValue(_pi.ProjectID, "ClientSocket_Heartbeat_Rep")

        Dim frm As New ConnectConfigForm(parameters)
        If frm.ShowDialog() = Windows.Forms.DialogResult.OK Then
            KeyValuePairClass.SetValue(_pi.ProjectID, "ClientSocket_Heartbeat_IdleTime", parameters(0))
            KeyValuePairClass.SetValue(_pi.ProjectID, "ClientSocket_Heartbeat_WaitTime", parameters(1))
            KeyValuePairClass.SetValue(_pi.ProjectID, "ClientSocket_Heartbeat_Rep", parameters(2))
        End If
    End Sub

End Class